package com.cositas.dulces.lp.promo2012;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cositas.dulces.lp.promo2012.dbentities.Participant;
import com.cositas.dulces.lp.promo2012.dbentities.WallShare;
import com.cositas.dulces.lp.promo2012.utils.ActionsPoints;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class WallShareAction implements Action {
	
	public void doAction(HttpServletRequest req, HttpServletResponse resp) throws EntityNotFoundException, IOException {
		String uid = req.getParameter("uid"); // el que invita
		String opt = req.getParameter("opt"); // el que invita
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Key wallShareKey = KeyFactory.createKey(WallShare.entity_name, uid + "-" + opt);
		try {
			datastore.get(wallShareKey);
		} catch (EntityNotFoundException e) {
			// circuito de puntaje
			Key participantKey = KeyFactory.createKey(Participant.entity_name, uid);
			Entity participant = datastore.get(participantKey);
			Integer account = Integer.valueOf((String)participant.getProperty(Participant.field_points));
			account = account + ActionsPoints.WALL_SHARE_POINTS;
			participant.setProperty(Participant.field_points, account.toString());
			datastore.put(participant);
			Entity wallShare = new Entity(wallShareKey);
			datastore.put(wallShare);
		}
		resp.getWriter().print("OK");
	}
}
